<template>
  <div>
    <!--面包屑区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片区域-->
    <el-card>
      <!--添加分类-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="openAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <!--数据table展示区-->
      <table-tree class="tableTree" :data="goodsCateList" :columns="columns"
                  show-index index-text="#" border
                  :expand-type="false" :selection-type="false"
                  :show-row-hover="false">
        <template slot="valid" slot-scope="scope">
          <i class="el-icon-success" style="color: lightgreen" v-if="!scope.row.cat_deleted"></i>
          <i class="el-icon-error" style="color: red" v-if="scope.row.cat_deleted"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-if="scope.row.cat_level === 2">三级</el-tag>
        </template>

        <template slot="opt" slot-scope="scope">
          <el-button type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </table-tree>

      <!--分页区-->
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加分类 对话框-->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      @close="closeAddDialog"
      width="50%">
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="80px">
        <el-form-item label="分类名称"  prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            :options="goodsCateList"
            v-model="selectKeys"
            :props="cascaderProps"
            clearable
            @change="parentCateChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCate">确 定</el-button>
  </span>
    </el-dialog>

    <!--更改分类对话框-->
    <el-dialog
      title="编辑分类"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="100px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editCate">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
    export default {
        data() {
            return {
                goodsCateList: [],
                queryInfo: {
                    type: 3,
                    pagenum: 1,
                    pagesize: 5
                },
                total: 0,
                addCateDialogVisible: false,
                columns: [
                    {
                        label: '分类名称',
                        prop: 'cat_name',
                    },
                    {
                        label: '是否有效',
                        type: 'template',
                        template: 'valid'
                    },
                    {
                        label: '排序',
                        type: 'template',
                        template: 'order'
                    },
                    {
                        label: '操作',
                        type: 'template',
                        template: 'opt'
                    },
                ],
                addForm: {
                    cat_name: '',
                    cat_pid: 0,
                    cat_level: 0
                },
                selectKeys: [],
                //级联选择器的配置项
                cascaderProps: {
                    label: 'cat_name',
                    value: 'cat_id',
                    children: 'children',
                    expandTrigger: 'hover',
                    checkStrictly: true,
                },
                addFormRules: {
                    cat_name: [
                        {required: true, message: '请输入分类名称', trigger: 'blur'},
                        {min: 5, max: 10, message: '5到10个字符', trigger: 'blur'}
                    ]
                },
                editDialogVisible: false,
                editForm: {
                    cat_name: '',
                    cat_id: '',
                },
                editFormRules: {
                    cat_name: [
                        { required: true, message: '请输入分类名称', trigger: 'blur' },
                        { min: 5, max: 10, message: '5到10个字符', trigger: 'blur' },
                    ],
                },
            }
        },
        created() {
            this.getGoodsCateList();
        },
        methods: {
            async getGoodsCateList() {
                const {data: res} = await this.$http.get('/categories', {params: this.queryInfo})
                if (res.meta.status !== 200) {
                    return this.$message.error(res.meta.msg)
                }
                this.goodsCateList = res.data.result
                this.total = res.data.total
                console.log(this.goodsCateList)
            },
            // 改变单页大小
            sizeChange(newSize) {
                this.queryInfo.pagesize = newSize
                this.getGoodsCateList()
            },
            // 改变当前页码
            currentChange(currentPage) {
                this.queryInfo.pagenum = currentPage
                this.getGoodsCateList()
            },
            // 打开添加商品分类对话框
            openAddCateDialog() {
                this.addCateDialogVisible = true
            },
            // 当级联项发生改变是出发
            parentCateChange(){
                if (this.selectKeys.length > 0) {
                    // 为当前分类父分类id赋值
                    this.addForm.cat_pid = this.selectKeys[this.selectKeys.length -1]
                    // 为当前分类等级赋值
                    this.addForm.cat_level = this.selectKeys.length
                } else {
                    // 为当前分类父分类id赋值
                    this.addForm.cat_pid = 0
                    // 为当前分类等级赋值
                    this.addForm.cat_level = 0
                }
            },
            addCate() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return this.$message.error('校验失败')
                    }
                    const {data: res} = await this.$http.post('categories', this.addForm)
                    if (res.meta.status !== 201) {
                        return this.$message.error('分类创建失败')
                    }
                    this.$message.success('分类创建成功')

                    this.getGoodsCateList()
                    this.addCateDialogVisible = false

                })
            },
            closeAddDialog() {
                this.$refs.addFormRef.resetFields()
                this.selectKeys = ''
                this.addForm.cat_level = 0
                this.addForm.cat_pid = 0
            },
            openEditDialog(cateInfo) {
                this.editDialogVisible = true
                this.editForm.cat_id = cateInfo.cat_id
                this.editForm.cat_name = cateInfo.cat_name
            },
            editCate() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return this.$message.error('数据校验失败')
                    }

                    const {data: res} = await this.$http.put('categories/' + this.editForm.cat_id, {cat_name:
                        this.editForm.cat_name})
                    if (res.meta.status !== 200) {
                        return this.$message.error('更新失败')
                    }
                    this.getGoodsCateList()
                    this.$message.success('更新成功')
                    this.editDialogVisible = false
                })
            },
            async deleteCate(cat_id) {
                const confirmRes = await this.$confirm('此操作将永久删除该商品分类, 是否继续?','提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (confirmRes !== 'confirm') {
                    return this.$message.info('取消删除成功')
                }
                const {data: res} = await this.$http.delete(`categories/${cat_id}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                this.getGoodsCateList()
            },
        }

    }
</script>

<style scoped>
  .tableTree {
    margin-top: 15px;
  }
  .el-cascader {
    width: 100%;
  }
</style>
